package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * Mybatis支持*匹配扫描包
 *
 * @author ruoyi
 */
@Configuration
public class MyBatisConfig {

    @Autowired
    private Environment env;

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        // 优先使用mybatis-plus的配置，如果没有则使用mybatis的配置
        String typeAliasesPackage = env.getProperty("mybatis-plus.type-aliases-package",
                env.getProperty("mybatis.typeAliasesPackage"));

        String mapperLocations = env.getProperty("mybatis-plus.mapper-locations",
                env.getProperty("mybatis.mapperLocations"));

        String configLocation = env.getProperty("mybatis-plus.config-location",
                env.getProperty("mybatis.configLocation"));

        // 使用MyBatis-Plus的SqlSessionFactoryBean
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // 设置类型别名包
        if (StringUtils.hasText(typeAliasesPackage)) {
            sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
        }

        // 设置mapper位置
        if (StringUtils.hasText(mapperLocations)) {
            sessionFactory.setMapperLocations(
                    new PathMatchingResourcePatternResolver().getResources(mapperLocations)
            );
        }

        // 设置配置文件位置
        if (StringUtils.hasText(configLocation)) {
            sessionFactory.setConfigLocation(
                    new DefaultResourceLoader().getResource(configLocation)
            );
        }

        return sessionFactory.getObject();
    }
}